package com.matrix.draft.sockettest.day12;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class FutureKeeper {

    public static AtomicLong sequenceId = new AtomicLong(0);

    public static final Map<Long, CompletableFuture> futures = new ConcurrentHashMap<>();

    public static CompletableFuture doTask(Long thing) {
        CompletableFuture<Object> future = new CompletableFuture<>();
        futures.put(thing, future);
        new Thread(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            future.complete(thing + " OK");
            futures.remove(thing);
        });
        return future;
    }

    public static void main(String[] args) throws Exception {

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    long st = System.currentTimeMillis();
                    long thing = RandomUtil.randomLong();
                    System.out.println("Send..."+thing);
                    CompletableFuture future = doTask(thing);
                    String result = (String) future.get();
                    System.out.println(result + " 完成,耗时" + (System.currentTimeMillis() - st));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }).start();
        }


        // Thread.sleep(Integer.MAX_VALUE);

    }

}
